/*
 * Answer Class by CintasFox
 *
 * Copyright (c) 2011 CintasFox
 */
#include "AnswerClass.h"


Answer::Answer()
{
	init(128);
}

Answer::Answer(int tlength)
{
	init(tlength);
}

Answer::~Answer()
{
}

int Answer::append(const char* appstr, int Type)
{
	if(AnswerString && SecString && appstr)
	{
		if (Type == 1)
		{
			errno_t terr = cat(SecString, appstr);
			if (terr == STRUNCATE)
			{
				return 4;
			}
			seccount = strlen(SecString);
		}
		if (count+strlen(appstr)+1 > length)
		{
			mode = 1;
			return 0;
		}
		else
		{
			errno_t terr = cat(AnswerString, appstr);
			if(terr)
			{
				return 3;
			}
			count = strlen(AnswerString);
			return 0;
		}
	}
	else
	{
		return 1;
	}
}

errno_t Answer::cat(char* dest, const char* source)
{
#ifdef _WINDOWS
	return strncat_s(dest, length*sizeof(char), source, _TRUNCATE);
#else
	if(strlen(dest)+strlen(source)+1<=length)
	{
		strncat(dest, source, strlen(source));
		dest[strlen(dest)]='\0';
		return 0;
	}
	return 1;
#endif
}

void Answer::init(int tlength)
{

	void* Space = calloc(tlength, sizeof(char));
	void* SSpace = calloc(tlength, sizeof(char));
	if (Space == NULL || SSpace == NULL)
	{
		length = 0;
		if(Space)
		{
			free(Space);
		}
		AnswerString = NULL;
		if(SSpace)
		{
			free(SSpace);
		}
		SecString = NULL;
		count = 0;
		seccount = 0;
		mode = 0;
	}
	else
	{
		length = tlength;
		AnswerString = (char*)Space;
		SecString = (char*)SSpace;
		count = 1;
		seccount = 1;
		mode = 0;
	}
}

void Answer::clear()
{
	if(AnswerString)
	{
		free(AnswerString);
		AnswerString = NULL;
	}
	if(SecString)
	{
		free(SecString);
		SecString = NULL;
	}
	count = 0;
	seccount = 0;
	length = 0;
	mode = 0;
}

char* Answer::giveAnswer()
{
	if(mode)
	{
		if (SecString)
		{
			return SecString;
		}
	}
	else
	{
		if(AnswerString)
		{
			return AnswerString;
		}
	}
	return NULL;
}

void Answer::clearAnswer(int tlength)
{
	//sichern
	if(tlength == 0)
	{
		if (length == 0)
		{
			tlength = 128;
		}
		else
		{
			tlength = length;
		}
	}
	//aufräumen
	clear();
	//neu holen
	init(tlength);
}

int Answer::check()
{
	if (AnswerString == NULL || SecString == NULL)
	{
		return 1;
	}
	else if(length == 0)
	{
		return 2;
	}
	else if(count >= length || seccount >= length)
	{
		return 3;
	}
	else
	{
		return 0;
	}
}